package com.example.handlerdemo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;

public class AsyncTaskActivity extends AppCompatActivity {
    private static final String TAG = "AsyncTaskActivity";
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refresh);
        btn = (Button) findViewById(R.id.btn);
        // 开启一个子线程，去执行异步任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "run, thread name:"  + Thread.currentThread().getName());
                MyAsyncTask asyncTask = new MyAsyncTask();
                asyncTask.execute();
            }
        }).start();
    }

    // 自定义AsyncTask，并重写相关方法，并打印执行所在线程
    class MyAsyncTask extends AsyncTask<Void, Integer, Void>{

        @Override
        protected Void doInBackground(Void... voids) {
            Log.e(TAG, "doInBackground, thread name:"  + Thread.currentThread().getName());
            // 模拟耗时任务
            for (int i = 0; i < 5; i ++) {
                SystemClock.sleep(1000);
                publishProgress(i);
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            Log.e(TAG, "onPreExecute, thread name:"  + Thread.currentThread().getName());
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Log.e(TAG, "onPostExecute, thread name:"  + Thread.currentThread().getName());
            btn.setText("执行完了！");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.e(TAG, "onProgressUpdate, thread name:"  + Thread.currentThread().getName());
        }
    }
}
